# 1. read data from csv
read_data <- function(csv_path="./datafix005.csv") {
  data <- read.csv(csv_path)
  return(data)
}


# 2. kmeans
pic_kmeans <- function(pic_data) {
  cl <- kmeans(pic_data, 2)
}

wssplot <- function(data, nc=15, seed=1234) {
  wss <- (nrow(data) - 1) * sum(apply(data, 2, var))
  for(i in 2:nc) {
    set.seed(seed)
    wss[i] <- sum(kmeans(data, centers=i)$withinss)
  }
  plot(1:nc, wss, type="b", xlab = "Number of Clusters", ylab="Within groups sum of squares")
}


#从CSV读取数据
frame <- read_data()
is.data.frame(frame)
#从读取到的数据中提取列trial，并去重
# trial_nums = unique(c(frame$trial))
trial_nums= c(1, 2, 3, 4, 5)
library(sqldf)
library(NbClust)
for (trail_num in trial_nums) {
  # 通过SQL语句查询指定trial的行
  pic_data = sqldf(paste0("select X,Y from frame where trial=", trail_num), row.names=TRUE)
  # pic_data = frame[frame$trial==trail_num,]
  print(pic_data)
  set.seed(1234)
  # 通过NbClust计算出最佳的分类数
  nc <- NbClust(pic_data, min.nc=2, max.nc=nrow(pic_data)-2, method="kmeans")
  pic_nc_best <- table(nc$Best.n[1,])
  best_nc = as.numeric(names(pic_nc_best[pic_nc_best == max(pic_nc_best)]))
  # k均值计算
  pic.kmeas <- kmeans(pic_data, best_nc)
  print(pic.kmeas$size)
  print(pic.kmeas$centers)
}